package com.fanfutian.eventproject.service.impl;

import com.fanfutian.eventproject.mapper.UserMapper;
import com.fanfutian.eventproject.pojo.User;
import com.fanfutian.eventproject.service.UserService;
import com.fanfutian.eventproject.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService{




    @Autowired
    private UserMapper userMapper;



    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    @Override
    public User findUserByUsername(String username) {
        return userMapper.findUserByUsername(username);
    }


    /**
     * 注册用户
     * @param username
     * @param password
     */
    @Override
    public void register(String username, String password) {
        // 对密码进行加密
        String md5DigestAsHexPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        // 添加用户
        userMapper.addUser(username, md5DigestAsHexPassword);
    }


    /**
     * 更新用户信息
     * @param user
     */
    @Override
    public void updateUserInfo(User user) {
        // 设置更新时间
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateUserInfo(user);
    }


    /**
     * 更新用户头像
     * @param avatarUrl
     */
    @Override
    public void updateUserAvatar(String avatarUrl) {
        // 获取用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer  userId =(Integer) map.get("id");
        userMapper.updateUserAvatar(avatarUrl, userId);
    }


    /**
     * 更新用户密码
     * @param newPwd
     */
    @Override
    public void updateUserPwd(String newPwd, Integer id) {
        log.info("修改用户密码········{}",newPwd);
        userMapper.updateUserPwd(newPwd,id);
    }
}
